package com.mj.haier.calc.servlet.impl;

import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mj.haier.calc.client.RrskxClient;
import com.mj.haier.calc.domain.AzEorderSettlementProcess;
import com.mj.haier.calc.domain.CarsTeamInfo;
import com.mj.haier.calc.servlet.Filter;
import com.mj.haier.calc.servlet.FilterChain;
import com.mj.haier.calc.servlet.Request;
import com.mj.haier.calc.servlet.Response;
import com.mj.haier.calc.servlet.ServletException;

import org.apache.commons.lang3.StringUtils;

public class CarsteamFilter implements Filter {

    private final Logger log = LoggerFactory.getLogger(CarsteamFilter.class);
    private final RrskxClient rrskxClient;

    public CarsteamFilter(RrskxClient rrskxClient){
        this.rrskxClient = rrskxClient;
    }


    @Override
    public void doFilter(Request req, Response res, FilterChain chain) throws IOException, ServletException {
        
        AzEorderSettlementProcess process = (AzEorderSettlementProcess)req.getObject();
        log.debug("CarsteamFilter 过滤前 AzEorderSettlementProcess: {}", process.toString());

        if("0".equals(process.getCarsTeamCompliance())){
            chain.doFilter(req, res);
            return;
        }
        
        String netpoint = process.getServerInfoCode();
        List<CarsTeamInfo> list = rrskxClient.searchCarsTeamInfosByNetpoint(netpoint);
        if(list.size() > 0){
            CarsTeamInfo carsTeamInfo = list.get(0);
            process.carsTeamId(carsTeamInfo.getCarsTeamId())
                .carsTeamName(carsTeamInfo.getCarsTeamName())
                .carsTeamTel(carsTeamInfo.getCarsTeamTel())
                .carsTeamCode(carsTeamInfo.getCarsTeamCode());
        }
        //验证合规性
        //车队编码，合规性必须; 车队名称，合规性必须; 车队V码， 合规性必须
        String compliance = "0";
        StringBuilder complianceSb = new StringBuilder();
        if(StringUtils.isBlank(process.getCarsTeamId())){
            compliance = "1";
            complianceSb.append("车队编码必须, 但不合规").append("&");
        }
        if(StringUtils.isBlank(process.getCarsTeamName())){
            compliance = "1";
            complianceSb.append("车队名称必须, 但不合规").append("&");
        }
        if(StringUtils.isBlank(process.getCarsTeamCode())){
            compliance = "1";
            complianceSb.append("车队V码必须, 但不合规").append("&");
        }

        if("0".equals(compliance)){
            complianceSb.append("车队信息合规").append("&");
        }
        process.carsTeamCompliance(compliance).carsTeamMsg(complianceSb.toString());
        log.debug("CarsteamFilter 过滤之后 AzEorderSettlementProcess: {}", process.toString());
        chain.doFilter(req, res);
    }
}